package com.ecb.business.schedule;

import com.ecb.business.constant.AuditConstant;
import com.ecb.business.service.AuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:xuzheng
 * @Despriction:
 * @Date: Created in 2024/3/6 11:19
 * @Modify By: xuzheng
 */
@Slf4j
@Component
public class ScheduleTask {
    @Autowired
    private AuditService auditService;
    @Value("${audit.reportList:chain,node,org,evidence,contract,config,user}")
    private String reportList;

    @Scheduled(cron = "0 0 22 * * ?") //每天晚上十点进行整理
    public void generateAuditReport() {
        log.info("开始生成审计报告");
        Date date = new Date();
        // 一天前
        Date beforeDate = new Date(date.getTime() - 24 * 60 * 60 * 1000);
        log.info("报告开始时间：" + beforeDate);
        log.info("报告结束时间：" + date);
        String[] split = reportList.split(",");
        Map<String, Object> finalMap = new HashMap<>(); // 最终输出的报表
        for (String s : split) {
            List<Map> allByCreateTimeBetweenAndOperateTarget = auditService.findAllByCreateTimeBetweenAndOperateTarget(beforeDate, date, AuditConstant.OPERATE_TARGET_CONTRACT);
            finalMap.put(s, allByCreateTimeBetweenAndOperateTarget);
        }
        // 生成审计报告至文件
        File file = new File("auditReport.txt");
        try {
            file.createNewFile();
//            FileUtils.writeFile(file, finalMap);
            log.info("审计报告生成完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("审计报告生成完毕");

    }

}
